package com.redwine.app.adapter;

import android.content.Context;
import android.content.Intent;
import android.text.Spannable;
import android.text.SpannableString;
import android.text.style.ForegroundColorSpan;
import android.view.LayoutInflater;
import android.view.View;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.android.volley.Request;
import com.android.volley.Response;
import com.android.volley.VolleyError;
import com.redwine.app.APP;
import com.redwine.app.ProcurementDetailActivity;
import com.redwine.app.R;
import com.redwine.app.PublishedSourcesDetailActivity;
import com.redwine.app.net.GsonRequest;
import com.redwine.app.net.NetworkConstants;
import com.redwine.app.net.responses.BaseResponse;
import com.redwine.app.net.responses.MyCollectionProcurementResponse;
import com.redwine.app.net.responses.MyCollectionSupplyResponse;
import com.redwine.app.net.responses.SendMsgEvent;
import com.redwine.app.utils.BitmapUtils;
import com.redwine.app.utils.Global;
import com.redwine.app.utils.Utils;

import java.util.ArrayList;
import java.util.LinkedHashMap;
import java.util.List;
import java.util.Map;

import de.greenrobot.event.EventBus;

/**
 * 我的收藏页面适配器
 * 作者：gassion on 17/9/5 15:57
 * 最可怕的敌人，就是没有坚强的信念。
 */
public class MyCollectionAdapter extends BaseAdapter {

    private Context context;

    private List<MyCollectionSupplyResponse.DataEntityX.DataEntity> datalist;
    private List<MyCollectionProcurementResponse.DataEntityX.DataEntity> dataEntities;//采购商


    public MyCollectionAdapter(Context context) {
        this.context = context;
    }


    /**
     * 设置供应
     *
     * @param datalist
     */
    public void setData(int page, List<MyCollectionSupplyResponse.DataEntityX.DataEntity> datalist) {
        if (page > 1) {
            if (null != this.datalist && !this.datalist.isEmpty())
                this.datalist.addAll(datalist);

        } else {
            if (null != this.datalist && !this.datalist.isEmpty())
                this.datalist = new ArrayList<>();
            this.datalist = datalist;
        }
        notifyDataSetChanged();
    }

    /**
     * 设置采购数据
     *
     * @param dataEntities
     */
    public void setProcurementData(int page, List<MyCollectionProcurementResponse.DataEntityX.DataEntity> dataEntities) {
        if (page > 1) {
            if (null != this.dataEntities && !this.dataEntities.isEmpty())
                this.dataEntities.addAll(dataEntities);

        } else {
            if (null != this.dataEntities && !this.dataEntities.isEmpty())
                this.dataEntities = new ArrayList<>();
            this.dataEntities = dataEntities;
        }
        notifyDataSetChanged();
    }

    @Override
    public int getCount() {
        if (null != datalist) {
            return datalist.size();
        } else if (null != dataEntities) {
            return dataEntities.size();
        } else {
            return 0;
        }
    }

    @Override
    public Object getItem(int position) {
        if (null != datalist) {
            return datalist.get(position);
        } else if (null != dataEntities) {
            return dataEntities.size();
        } else {
            return null;
        }
    }

    @Override
    public long getItemId(int position) {
        return position;
    }

    @Override
    public View getView(int position, View convertView, ViewGroup parent) {
        ViewHolder viewHolder;
        if (convertView == null) {
            LayoutInflater layoutInflater = LayoutInflater.from(context);
            convertView = layoutInflater.inflate(R.layout.activity_my_collection_item, parent, false);
            viewHolder = new ViewHolder(convertView);
            convertView.setTag(viewHolder);
        } else {
            viewHolder = (ViewHolder) convertView.getTag();
        }
        if (null != datalist) {
            final MyCollectionSupplyResponse.DataEntityX.DataEntity dataEntity = datalist.get(position);
            final MyCollectionSupplyResponse.DataEntityX.DataEntity.PublishInfoEntity publish_info = dataEntity.getPublish_info();
            BitmapUtils.loadImage(viewHolder.itemIvShopPic, publish_info.getPic(), BitmapUtils.THE_ARTICLE);
            viewHolder.itemTvShopName.setText(publish_info.getName());
            viewHolder.itemTvDate.setText(publish_info.getDate());
            viewHolder.itemTvPrice.setText(publish_info.getPrice());
            viewHolder.itemTvCity.setText(publish_info.getCity());
            viewHolder.itemLlQuoteCount.setVisibility(View.INVISIBLE);
            SpannableString spannableString = new SpannableString(publish_info.getNum() + "人报价");
            ForegroundColorSpan backgroundColorSpan = new ForegroundColorSpan(context.getResources().getColor(R.color.color_e82565));
            spannableString.setSpan(backgroundColorSpan, 0, publish_info.getNum().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            viewHolder.itemTvOfferCount.setText(spannableString);
            Utils.setSupplierStatus(viewHolder.itemTvShoppingStatus, Integer.valueOf(publish_info.getStatusX()));
            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, PublishedSourcesDetailActivity.class);
                    intent.putExtra(PublishedSourcesDetailActivity.SHOP_NAME, publish_info.getName());
                    intent.putExtra(PublishedSourcesDetailActivity.SHOP_UID, publish_info.getUid());
                    intent.putExtra(PublishedSourcesDetailActivity.SHOP_ID, publish_info.getId());
                    context.startActivity(intent);
                }
            });
            viewHolder.itemTvCollectionStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    requestCancelCollectionData(dataEntity.getId());
                }
            });
        } else if (null != dataEntities) {
            final MyCollectionProcurementResponse.DataEntityX.DataEntity dataEntity = dataEntities.get(position);
            final MyCollectionProcurementResponse.DataEntityX.DataEntity.PurchaseInfoEntity purchase_info = dataEntity.getPurchase_info();
            BitmapUtils.loadImage(viewHolder.itemIvShopPic, purchase_info.getPic(), BitmapUtils.THE_ARTICLE);
            viewHolder.itemTvShopName.setText(purchase_info.getTitle());
            viewHolder.itemTvDate.setText(purchase_info.getDate());
            viewHolder.itemTvPrice.setText(purchase_info.getPrice());
            viewHolder.itemTvCity.setText(purchase_info.getCity());
            viewHolder.itemLlQuoteCount.setVisibility(View.VISIBLE);
            SpannableString spannableString = new SpannableString(purchase_info.getQuote_count() + "人报价");
            ForegroundColorSpan backgroundColorSpan = new ForegroundColorSpan(context.getResources().getColor(R.color.color_e82565));
            spannableString.setSpan(backgroundColorSpan, 0, purchase_info.getQuote_count().length(), Spannable.SPAN_EXCLUSIVE_EXCLUSIVE);
            viewHolder.itemTvOfferCount.setText(spannableString);
            Utils.setProcurementStatus(viewHolder.itemTvShoppingStatus, Integer.valueOf(purchase_info.getStatusX()));
            switch (Integer.valueOf(purchase_info.getStatusX())) {

                case 2:
                    viewHolder.itemTvHasAs.setVisibility(View.VISIBLE);
                    viewHolder.itemTvHasAs.setText("已截止");
                    break;

                case 5:
                    viewHolder.itemTvHasAs.setVisibility(View.VISIBLE);
                    viewHolder.itemTvHasAs.setText("交易成功");
                    break;

                default:
                    viewHolder.itemTvHasAs.setVisibility(View.INVISIBLE);
                    break;

            }

            convertView.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    Intent intent = new Intent(context, ProcurementDetailActivity.class);
                    intent.putExtra(PublishedSourcesDetailActivity.SHOP_NAME, purchase_info.getTitle());
                    intent.putExtra(PublishedSourcesDetailActivity.SHOP_UID, purchase_info.getUid());
                    intent.putExtra(PublishedSourcesDetailActivity.SHOP_ID, purchase_info.getId());
                    context.startActivity(intent);
                }
            });
            viewHolder.itemTvCollectionStatus.setOnClickListener(new View.OnClickListener() {
                @Override
                public void onClick(View v) {
                    requestCancelCollectionData(dataEntity.getId());
                }
            });
        }
        return convertView;
    }


    public static class ViewHolder {
        public View rootView;
        public ImageView itemIvShopPic;
        public TextView itemTvShopName;
        public TextView itemTvHasAs;
        public TextView itemTvCollectionStatus;
        public TextView itemTvDate;
        public TextView itemTvOfferCount;
        public TextView itemTvPrice;
        public TextView itemTvCity;
        public TextView itemTvShoppingStatus;
        public LinearLayout itemLlQuoteCount;

        public ViewHolder(View rootView) {
            this.rootView = rootView;
            this.itemIvShopPic = (ImageView) rootView.findViewById(R.id.item_iv_shop_pic);
            this.itemTvShopName = (TextView) rootView.findViewById(R.id.item_tv_shop_name);
            this.itemTvHasAs = (TextView) rootView.findViewById(R.id.item_tv_has_as);
            this.itemTvCollectionStatus = (TextView) rootView.findViewById(R.id.item_tv_collection_status);
            this.itemTvDate = (TextView) rootView.findViewById(R.id.item_tv_date);
            this.itemTvOfferCount = (TextView) rootView.findViewById(R.id.item_tv_offer_count);
            this.itemTvPrice = (TextView) rootView.findViewById(R.id.item_tv_price);
            this.itemTvCity = (TextView) rootView.findViewById(R.id.item_tv_city);
            this.itemTvShoppingStatus = (TextView) rootView.findViewById(R.id.item_tv_shopping_status);
            this.itemLlQuoteCount = (LinearLayout) rootView.findViewById(R.id.item_ll_quote_count);
        }

    }

    /**
     * 取消收藏
     */
    private void requestCancelCollectionData(String collection_id) {
        String url = NetworkConstants.CANCLE_COLLECTION_URL;
        Map<String, String> params = new LinkedHashMap<>();
        params.put("uid", Global.user.getUid());
        params.put("collection_id", collection_id);
        GsonRequest<BaseResponse> request = new GsonRequest<>(url, Request.Method.POST,
                BaseResponse.class, false, params, new Response.Listener<BaseResponse>() {
            @Override
            public void onResponse(BaseResponse response) {
                if (response.isSuccess()) {
                    EventBus.getDefault().post(new SendMsgEvent(SendMsgEvent.REFURBISH_MY_COLLECTION));
                } else {
                    Utils.showToast(response.getMsg());
                }
            }
        }, new Response.ErrorListener() {
            @Override
            public void onErrorResponse(VolleyError error) {
                Utils.showToast(error.getMessage());
            }
        });
        APP.getInstance().getRequestQueue().add(request);
    }
}
